package com.qcdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

//redis全局id生成器
@Component
public class RedisIdWork {
    //代表我们的起始时间 ：2022-05-01-0-0-0
    private static final long BEGIN_TIME= 1651363200L;

    //指定我们序列key的前缀
    private static final String KEY_PREFIX="icr:";

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    public long nextId(String key){
        //1.符号位我不用关注
        //2.时间戳信息
        long currentTime = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        //2.1增强我们时间戳安全性
        long time = currentTime - BEGIN_TIME;
        //3.获取我们的序列值（使用redis来生成
        //3.1 序列号的安全性：每天都让他重新产生一个新的序列(2022:06:04)
        String dateTimeFormat = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));

        long increment = stringRedisTemplate.opsForValue().increment(KEY_PREFIX+key+":"+dateTimeFormat);

        long id = time << 32 | increment;

        return  id;
    }

    public static void main(String[] args) {
        //long cutime = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        //System.out.println(cutime);
        //获取2022-05-01-0-0-0
        //long l = LocalDateTime.of(2022, 5, 1, 0, 0, 0).toEpochSecond(ZoneOffset.UTC);
        //System.out.println(l);
        long i = 2968501L + 1651363200L;
        System.out.println(i);
    }
}
